"""认证模块序列化器"""
from rest_framework import serializers
from django.contrib.auth.models import User
from django.contrib.auth.password_validation import validate_password
from rest_framework.validators import UniqueValidator

class UserRegistrationSerializer(serializers.ModelSerializer):
    """用户注册序列化器"""
    email = serializers.EmailField(
        required=True,
        validators=[UniqueValidator(queryset=User.objects.all(), message="该邮箱已被注册")]
    )
    password = serializers.CharField(
        write_only=True,
        required=True,
        validators=[validate_password],
        style={'input_type': 'password'},
        help_text="密码长度至少8位，不能是常见密码"
    )
    password_confirm = serializers.CharField(
        write_only=True,
        required=True,
        style={'input_type': 'password'},
        help_text="确认密码"
    )
    first_name = serializers.CharField(required=True, help_text="名字")
    last_name = serializers.CharField(required=True, help_text="姓氏")

    class Meta:
        model = User
        fields = '__all__'  # 🔑 关键：统一使用 '__all__'
        read_only_fields = ['id', 'is_active', 'is_staff', 'is_superuser', 'date_joined', 'last_login', 'groups', 'user_permissions']
        extra_kwargs = {
            'username': {
                'validators': [UniqueValidator(queryset=User.objects.all(), message="该用户名已被使用")]
            },
            'password': {'write_only': True},
            'password_confirm': {'write_only': True}
        }

    def validate(self, attrs):
        """验证密码确认"""
        if attrs['password'] != attrs['password_confirm']:
            raise serializers.ValidationError({"password_confirm": "两次输入的密码不一致"})
        return attrs

    def create(self, validated_data):
        """创建用户"""
        validated_data.pop('password_confirm', None)
        user = User.objects.create_user(**validated_data)
        return user

class UserProfileSerializer(serializers.ModelSerializer):
    """用户信息序列化器"""
    full_name = serializers.SerializerMethodField(help_text="全名")
    date_joined = serializers.DateTimeField(read_only=True, help_text="注册时间")
    last_login = serializers.DateTimeField(read_only=True, help_text="最后登录时间")

    class Meta:
        model = User
        fields = '__all__'  # 🔑 关键：统一使用 '__all__'
        read_only_fields = ['id', 'username', 'is_active', 'is_staff', 'is_superuser', 'date_joined', 'last_login', 'groups', 'user_permissions']

    def get_full_name(self, obj) -> str:
        """获取全名"""
        return f"{obj.last_name}{obj.first_name}" if obj.last_name and obj.first_name else obj.username

class ChangePasswordSerializer(serializers.Serializer):
    """修改密码序列化器"""
    old_password = serializers.CharField(
        required=True,
        style={'input_type': 'password'},
        help_text="当前密码"
    )
    new_password = serializers.CharField(
        required=True,
        validators=[validate_password],
        style={'input_type': 'password'},
        help_text="新密码"
    )
    new_password_confirm = serializers.CharField(
        required=True,
        style={'input_type': 'password'},
        help_text="确认新密码"
    )

    def validate(self, attrs):
        """验证密码"""
        if attrs['new_password'] != attrs['new_password_confirm']:
            raise serializers.ValidationError({"new_password_confirm": "两次输入的新密码不一致"})
        return attrs

    def validate_old_password(self, value):
        """验证当前密码"""
        user = self.context['request'].user
        if not user.check_password(value):
            raise serializers.ValidationError("当前密码错误")
        return value


class TokenResponseSerializer(serializers.Serializer):
    """JWT Token响应序列化器"""
    access = serializers.CharField(help_text="访问令牌")
    refresh = serializers.CharField(help_text="刷新令牌", required=False)
